package socket1;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务器");
            socket = new Socket("localhost",8080);
            System.out.println("服务端连接成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner input = new Scanner(System.in);
            System.out.println("请输入昵称：");
            while(true){
                String nickname = input.nextLine();
                if(nickname.trim().isEmpty()){
                    System.out.println("输入为空，请重新输入");
                }else{
                    pw.println(nickname);
                    break;
                }

            }
            ServerHandler serverHandler = new ServerHandler();
            Thread readMessage = new Thread(serverHandler);
            readMessage.setDaemon(true);
            readMessage.start();



            while(true){
                String sendMessage = input.nextLine();
                if("exit".equalsIgnoreCase(sendMessage)){
                    break;
                }
                pw.println(sendMessage);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br =new BufferedReader(isr);
                String messageFromServer;
                while((messageFromServer = br.readLine())!=null){
                    System.out.println(messageFromServer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();//四次挥手
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static void main(String[] args){
        Client client = new Client();
        client.start();
    }
}
